package com.ljh.localmusic.data.local

import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import com.ljh.localmusic.runtime.App
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map

/**
 * author：LJH on 2025/9/18 09:29
 *
 */

object DataStoreProvider {
    val dataStore: DataStore<Preferences> by lazy {
        PreferenceDataStoreFactory.create(
            corruptionHandler = ReplaceFileCorruptionHandler {
                // 当文件损坏时，清空恢复（避免崩溃）
                emptyPreferences()
            },
            produceFile = {
                App.app.preferencesDataStoreFile("data_store")  // 保持和之前相同文件名
            }
        )
    }
}


/**
 * 安全读取 DataStore key 的扩展方法
 */
fun <T> DataStore<Preferences>.safeRead(
    key: Preferences.Key<T>,
    defaultValue: T
): Flow<T> {
    return this.data
        .catch { exception ->
            // 捕获异常，避免 app 崩溃（如 CorruptionException）
            exception.printStackTrace()
            emit(emptyPreferences())
        }
        .map { preferences ->
            preferences[key] ?: defaultValue
        }
}

suspend fun safeEditDataStore(
    block: suspend (MutablePreferences) -> Unit
): Boolean {
    return try {
        DataStoreProvider.dataStore.edit(block)
        true
    } catch (e: Exception) {
        e.printStackTrace()
        false
    }
}


object AppCache {

    private val KEY_MUSIC_LIST = stringPreferencesKey("key_music_list")

    val cacheMusicList = DataStoreProvider.dataStore.safeRead(KEY_MUSIC_LIST, "")

    suspend fun refreshCacheMusicList(musicList: String) {
        safeEditDataStore {
            it[KEY_MUSIC_LIST] = musicList
        }
    }
}


